from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QDialog, QGridLayout, QMenu
from PySide6.QtGui import QCursor
from .widgets.panels import BasePanel
from .widgets.table_widget import CommonTableWidget
from .widgets.dialogs import BaseDialog, MessageOverlay
from .widgets.basewidgets import *
from api import api
from common import config, utils
from decimal import Decimal

CUSTOMER_HEADER_COLUMNS = {
    "联系人": {"type": "text", "text": lambda x: x["contact"]},
    "联系电话": {"type": "text", "text": lambda x: x["phone"]},
    "微信": {"type": "text", "text": lambda x: x["wechat"] or "--"},
    "累计消费": {"type": "text", "text": lambda x: f"{x['total_amount']:.2f}"},
    "操作": {"type": "action"}
}

class CustomerPage(BasePanel):
    def __init__(self):
        super().__init__("客户管理")
        self.setup_ui()
        self.setup_context_menu()
        
    def setup_ui(self):
        # 搜索和操作区域
        search_widget = SearchPanel()
        search_layout = QHBoxLayout(search_widget)
        
        # 搜索框
        self.search_input = SearchLineEdit()
        self.search_input.setPlaceholderText("根据客户名/电话/微信搜索")
        self.search_input.textChanged.connect(self.flush_table)
        
        # 消费金额筛选 TODO: 后期添加
        #self.amount_combo = NormalComboBox()
        #self.amount_combo.setItems({
        #    "全部金额": "",
        #    "1万以下": "0-10000",
        #    "1-5万": "10000-50000",
        #    "5万以上": "50000-"
        #})
        #self.amount_combo.currentIndexChanged.connect(self.flush_table)
        
        # 添加客户按钮
        add_btn = BluePushButton("添加客户")
        add_btn.clicked.connect(self.show_add_customer_dialog)
        
        search_layout.addWidget(self.search_input)
        #search_layout.addWidget(self.amount_combo)
        search_layout.addStretch()
        search_layout.addWidget(add_btn)
        
        self.main_layout.addWidget(search_widget)
        
        # 客户表格
        table_widget = QWidget()
        table_widget.setObjectName("customerTable")
        table_layout = QVBoxLayout(table_widget)
        
        self.customer_table = CommonTableWidget(headers=CUSTOMER_HEADER_COLUMNS)
        self.customer_table.pageSizeChanged.connect(self.flush_table)
        self.customer_table.set_description("累计消费只统计已经付款的销售单(退货单不计入)")
        
        table_layout.addWidget(self.customer_table)
        self.main_layout.addWidget(table_widget)

    def setup_context_menu(self):
        super().setup_context_menu()
        self.customer_table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customer_table.customContextMenuRequested.connect(self.show_context_menu)

    def add_extra_context_menus(self, menu, pos):
        menu.addSeparator()
        add_customer_action = menu.addAction("添加客户")
        add_customer_action.triggered.connect(self.show_add_customer_dialog)
        
        # 如果是在表格中点击
        sender = self.sender()
        if sender == self.customer_table and self.customer_table.itemAt(pos):
            row = self.customer_table.itemAt(pos).row()
            customer_data = self.customer_table.get_row_data(row)
            
            menu.addSeparator()
            
            # 客户操作子菜单
            operations_menu = menu.addMenu("客户操作")
            operations_menu.addAction("编辑").triggered.connect(
                lambda: self.edit_customer(row))
            delete_action = operations_menu.addAction("删除")
            delete_action.triggered.connect(lambda: self.delete_customer(row))
            
            menu.addSeparator()
            
            # 客户信息子菜单
            info_menu = menu.addMenu("客户信息")
            info_menu.addAction(f"联系人: {customer_data['contact']}")
            info_menu.addAction(f"联系电话: {customer_data['phone']}")
            if customer_data.get('wechat'):
                info_menu.addAction(f"微信: {customer_data['wechat']}")
            info_menu.addAction(f"累计消费: {customer_data['total_amount']:.2f}({config.CURRENCY_UNIT})")
    
    def load_data(self):
        """初始加载数据"""
        self.flush_table()
    
    def flush_table(self):
        """刷新表格数据"""
        customers = api.get_customers(
            search=self.search_input.text(),
            extras=True,
            page=self.customer_table.current_page,
            per_page=self.customer_table.page_size
        )
        if not customers:
            return
            
        self.customer_table.set_total_items(customers["count"])
        self.customer_table.setRowCount(len(customers["items"]))
        for i, customer in enumerate(customers["items"]):
            self.customer_table.set_row_data(i, customer)
            action_buttons = [
                {"text": "编辑", "callback": self.edit_customer},
                {"text": "删除", "callback": self.delete_customer, "objectName": "deleteButton"}
            ]
            self.customer_table.add_action_buttons(i, action_buttons)
    
    def show_add_customer_dialog(self):
        """显示添加客户对话框"""
        dialog = CustomerFormDialog(self)
        if dialog.exec() == QDialog.Accepted:
            api.add_customer(**dialog.get_data())
            MessageOverlay.info(self, "客户添加成功")
            self.flush_table()
    
    def edit_customer(self, row):
        """编辑客户"""
        customer_data = self.customer_table.get_row_data(row)
        dialog = CustomerFormDialog(self, customer_data)
        if dialog.exec() == QDialog.Accepted:
            api.update_customer(customer_data["id"], **dialog.get_data())
            MessageOverlay.info(self, "客户信息更新成功")
            self.flush_table()
    
    def delete_customer(self, row):
        """删除客户"""
        customer_data = self.customer_table.get_row_data(row)
        if MessageOverlay.question(self, f"确定要删除客户 {customer_data['contact']} 吗？删除后将不能恢复！") == MessageOverlay.ACCEPTED:
            api.delete_customer(customer_data["id"])
            MessageOverlay.info(self, "客户删除成功")
            self.flush_table()

class CustomerFormDialog(BaseDialog):
    def __init__(self, parent=None, customer_data=None):
        super().__init__(parent)
        self.customer_data = customer_data
        self.setup_ui()
        
    def setup_ui(self):
        self.setWindowTitle("编辑客户" if self.customer_data else "添加客户")
        self.setMinimumWidth(300)
        
        layout = QVBoxLayout(self)
        
        # 表单布局
        form_layout = QGridLayout()
        
        # 联系人
        self.contact_input = NormalLineEdit()
        form_layout.addWidget(NormalLabel("联系人:"), 0, 0)
        form_layout.addWidget(self.contact_input, 0, 1)
        
        # 联系电话
        self.phone_input = NormalLineEdit()
        form_layout.addWidget(NormalLabel("联系电话:"), 1, 0)
        form_layout.addWidget(self.phone_input, 1, 1)
        
        # 微信
        self.wechat_input = NormalLineEdit()
        form_layout.addWidget(NormalLabel("微信:"), 2, 0)
        form_layout.addWidget(self.wechat_input, 2, 1)
        
        layout.addLayout(form_layout)
        
        # 如果是编辑模式，填充现有数据
        if self.customer_data:
            self.contact_input.setText(self.customer_data["contact"])
            self.phone_input.setText(self.customer_data["phone"])
            self.wechat_input.setText(self.customer_data["wechat"] or "")
        
        # 按钮布局
        button_layout = self.create_button_layout(self.validate_and_accept)
        layout.addLayout(button_layout)
    
    def validate_and_accept(self):
        """验证表单数据"""
        if not self.contact_input.text():
            MessageOverlay.warning(self, "请输入联系人")
            self.contact_input.setFocus()
            return
            
        if not self.phone_input.text():
            MessageOverlay.warning(self, "请输入联系电话")
            self.phone_input.setFocus()
            return
        
        # 验证手机号格式
        if not utils.match_phone_number(self.phone_input.text()):
            MessageOverlay.warning(self, "请输入正确的手机号码")
            self.phone_input.setFocus()
            return
        
        self.accept()
    
    def get_data(self):
        """获取表单数据"""
        return {
            "contact": self.contact_input.text(),
            "phone": self.phone_input.text(),
            "wechat": self.wechat_input.text(),
        }
